package fms.core;

import fms.acarsMsgProcessUtil.DownLinkDatagramHeader;
import fms.acarsMsgProcessUtil.RawDatagram;
import fms.dao.CptSendService;
import fms.model.CptSend;
import fms.util.ConfUtil;
import fms.util.ObjectUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FlpFilter implements IFilter {
    private Logger logger = Logger.getLogger(FlpFilter.class);
    // 风温下行请求报文的SMI列表
    private List downQeqList = new ArrayList();

    public FlpFilter() {
        File fBaseParam = new File(ConfUtil.props.getProperty("baseParamFilePath"));
        final SAXReader readerBaseParam = new SAXReader();
        try {
            final Document paraseRulenDoc = readerBaseParam.read(fBaseParam);
            Element uniqueObject = (Element) paraseRulenDoc.selectSingleNode("/baseParamter/coreService/flpController/replySMI");
            String[] downQeqSMI = uniqueObject.getText().split(",");
            for (int i = 0; i < downQeqSMI.length; i++) {
                downQeqList.add(downQeqSMI[i]);
            }
        } catch (final DocumentException e) {
            logger.error(e.getMessage());
        }
    }

    // 判断当前报文是否是飞行计划请求报文
    public boolean isFilter(String aContent) {
//        logger.debug("[飞行计划请求报文过滤] 开始进行报文过滤...");
        if (aContent.contains("<?xml") && aContent.contains("<request>")) {
            return false;
        } else if (aContent.contains("<?xml") && aContent.contains("FMS")) {
                return false;
        } else{
            DownLinkDatagramHeader msgHeader = null;
            String msgText = "";
            try {
                msgHeader = DownLinkDatagramHeader.Parse(RawDatagram.GetHeader(aContent));
                msgText = RawDatagram.GetBody(aContent);
            } catch (Exception e) {
                logger.error("报文头解析出错！" + e.getMessage() + "\r\n出错报文为：\r\n" + aContent);
                // 报头解析异常，该报文不是正规的acars报文，可略过
                return false;
            }
            int indexofSMI=0;
            if(msgText.startsWith("/")){
                indexofSMI=msgText.indexOf(".")+1;
            }
            if (!ObjectUtil.isBlank(msgHeader.getSmi()) && (downQeqList.indexOf(msgHeader.getSmi()) >= 0) &&
                    !ObjectUtil.isBlank(msgText) && msgText.substring(indexofSMI, indexofSMI+6).equals("REQFPN")) {
                logger.debug("[飞行计划请求报文过滤] 该报文是飞行计划请求报！");
                /**
                 * 下面逻辑判断作用：仅对配置过的航空公司风温请求进行响应
                 * */
                String componystr = ConfUtil.props.getProperty("USEAIRCOMPANY");
                String componys[] = null;
                if(componystr != null) {
                    componys = componystr.split("\\,");
                }
                if (componys != null && !(ConfUtil.IsCanCompony(msgHeader.getFi().getAgencyID(), componys))) {
//                    logger.debug("[飞行计划请求报文过滤] 该航空公司" + msgHeader.getFi().getAgencyID() + "请求报文不是配置的航空公司，不予处理！");
                    return false;
                }
                return true;
            }
            else if (!ObjectUtil.isBlank(msgHeader.getSmi()) && (downQeqList.indexOf(msgHeader.getSmi()) >= 0) &&
                    !ObjectUtil.isBlank(msgText) && msgText.substring(0, 6).equals("REJFPN")) {
                int indexRej=msgText.indexOf("SN");
                String msgId=msgText.substring(indexRej+2,indexRej+12).trim();
                //更改数据库状态
                logger.debug("[飞行计划请求报文过滤] 发现‘FMS上传信息拒绝(REJFPN)报文’：" + aContent);
                CptSendService cptSendService = ConfUtil.getSingletonApplicationContextDao().getBean("cptSendService", CptSendService.class);
                List listsend = cptSendService.findCptSendbymsgId(msgId);
                if(listsend != null && listsend.size() > 0){
                    CptSend cptSend = (CptSend)listsend.get(0);
                    cptSend.setFmcrejection(msgText);
                    cptSendService.saveOrUpdate(cptSend);
                    logger.info("[飞行计划请求报文过滤，结束]飞机FMC下发的(风温/飞行计划)拒绝报文处理");
                }
                else{
                    logger.info("无法找到数据库中对应飞行计划ID："+msgId);
                }

                return  false;
            }
            else if(!ObjectUtil.isBlank(msgHeader.getSmi()) && (downQeqList.indexOf(msgHeader.getSmi()) >= 0) &&
                    !ObjectUtil.isBlank(msgText) && msgText.substring(0, 6).equals("RESFPN")){
                //RESFPN/AK6078480224\r\n,RESFPN/AC6078480224\r\n,RESFPN/RJ6078480224\r\n
                logger.info("[开始]飞机下发的(风温/飞行计划)回复(RESFPN)信息(AC/AK/RJ)处理");
                int indexRes=-1;
                if(msgText.contains("AK")){
                    indexRes=msgText.indexOf("AK");
                }
                if(msgText.contains("AC")){
                    indexRes=msgText.indexOf("AK");
                }
                if(msgText.contains("RJ")){
                    indexRes=msgText.indexOf("AK");
                }

                String operation=msgText.substring(indexRes,indexRes+2);
                String msgId=msgText.substring(indexRes+2,indexRes+12).trim();
                String status="";
                if(operation.equals("AK")){
//                    status="机载设备已确认";
                    status="5";
                }
                else if(operation.equals("AC")){
//                    status="机长已确认";
                    status="6";
                }
                else if(operation.equals("RJ")){
//                    status="机长已拒绝";
                    status="7";
                }
                else{
                    logger.info("收到原文："+msgText);
                }
                //更改数据库状态
                CptSendService cptSendService = ConfUtil.getSingletonApplicationContextDao().getBean("cptSendService", CptSendService.class);
                List listsend = cptSendService.findCptSendbymsgId(msgId);
                if(listsend != null && listsend.size() > 0){
                    CptSend cptSend = (CptSend)listsend.get(0);
                    cptSend.setSendStatus(status);
                    cptSendService.saveOrUpdate(cptSend);
                    logger.info("[结束]飞机下发的(风温/飞行计划)回复信息(AC/AK/RJ)处理");
                }
                else{
                    logger.info("无法找到数据库中对应飞行计划ID："+msgId);
                }
                return false;
            }
            else {
//                    logger.debug("[飞行计划请求报文过滤] 该报文不是飞行计划请求报文！");
                    return false;
            }
        }
	}
}